package com.ruoyi.common.utils.file;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.ruoyi.common.component.FileUploadResponse;
import com.ruoyi.common.config.QiniuFileStoreConfig;
import com.ruoyi.common.config.RuoYiConfig;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Locale;

/**
 * 七牛云文件存储工具类
 * 上传下载
 */
@Component
public class QiniuCloudFileStoreUtils {

    /**
     *
     * @param file 文件流
     * @return String 返回 文件访问地址
     */
    public String qiniuFileUpload(MultipartFile file) throws Exception
    {
        return qiniuFileUpload("",file,MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
    }
    /**
     *
     * @param baseDir 文件路径
     * @param file 文件流
     * @return String 返回 文件访问地址
     */
    public String qiniuFileUpload(String baseDir,MultipartFile file) throws Exception
    {
        return qiniuFileUpload(baseDir,file,MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
    }
    /**
     * @param baseDir 文件路径
     * @param file 文件流
     * @param allowedExtension 文件后缀
     * @return String 返回 文件访问地址
     */
    public String qiniuFileUpload(String baseDir,MultipartFile file, String[] allowedExtension) throws Exception
    {
        FileUploadUtils.assertAllowed(file, allowedExtension);
        //生成文件名称
        String fileName = FileUploadUtils.extractFilename(file);
        InputStream inputStream = file.getInputStream();
        //开启压缩开关并且 上传文件大于1MB才进行压缩
        if(RuoYiConfig.isThumbnails() && file.getSize() > 1*1024*1024)
        {
            //获取文件名称+后缀
            //String fileNameTemp = fileName.substring(fileName.lastIndexOf("/")+1);
            //获取文件后缀
            String ext = FileUploadUtils.getExtension(file);
            //判断是否是图片
            if(Arrays.asList(MimeTypeUtils.IMAGE_EXTENSION).contains(ext.toLowerCase()))
            {
                BufferedImage bufferedImage =  Thumbnails.of(file.getInputStream())
                        .scale(0.5)
                        .outputQuality(0.5).asBufferedImage();
                //.toFile("C:\\Users\\Administrator\\Desktop\\限时秒杀_files\\我的照片_163324_temp2.jpg");
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write(bufferedImage, ext, os); //图片写入到 ImageOutputStream
                inputStream = new ByteArrayInputStream(os.toByteArray());
            }
        }
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(getRegion(QiniuFileStoreConfig.getStoreRegion()));
        //设置请求协议为http
        //cfg.useHttpsDomains = false;
        //初始化上传管理器
        UploadManager uploadManager = new UploadManager(cfg);
        //鉴权
        Auth auth = Auth.create(QiniuFileStoreConfig.getAccessKey(), QiniuFileStoreConfig.getSecretKey());
        //上传token
        String upToken = auth.uploadToken(QiniuFileStoreConfig.getBucket());

        //存储到云盘中的路径+文件名称
        String key = QiniuFileStoreConfig.getRootDirectory()+"/"+(StringUtils.isBlank(baseDir)?"upload":baseDir)+"/"+fileName;
        try {
            //图片名称（包含路径，路径不存在会自动创建）
            Response response = uploadManager.put(inputStream, key, upToken,null,null);
            System.out.println(response.bodyString());
            //解析上传成功的结果
            DefaultPutRet putRet = JSONObject.parseObject(response.bodyString(), DefaultPutRet.class);
            return putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            throw new Exception(r.bodyString());
        }
    }

    /**
     * 删除单个文件
     * @param filePathName 路径+名称
     * @throws QiniuException
     */
    public void deleteSingleFile(String filePathName) throws QiniuException {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(getRegion(QiniuFileStoreConfig.getStoreRegion()));
        Auth auth = Auth.create(QiniuFileStoreConfig.getAccessKey(), QiniuFileStoreConfig.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        //路径的开头第一个斜杠需要去掉
        bucketManager.delete(QiniuFileStoreConfig.getBucket(), filePathName.startsWith("/")?filePathName.replaceFirst("/",""):filePathName);
    }
    /**
     * 获取 当前空间所在的存储区域
     * @return
     */
    public Region getRegion(String storeRegion)
    {
        Region region = null;
        switch (storeRegion)
        {
            //华东浙江2 区域
            case "huadongZheJiang2" :
                region = Region.huadongZheJiang2();
                break;
            //华北 区域
            case "huabei":
                region = Region.huabei();
                break;
            default:
                //华东区域
                region = Region.huadong();
        }
        return region;
    }
}
